import React, { useEffect, useMemo, useState } from "react";
import { message } from "antd";

import TableRender from "@/biz-components/table-render";
import { storage } from "@ey-utils/utils";
import moment from "moment";
import _ from "lodash";
import { xhrPostJson } from "@/services";
import ModalFormWrap from "./modal-form";
import ModalDetailForm from "./modal-detail-form";
import { getPageMeta } from "@/services/request/meta";
import { useEventsRegister, useInitData } from "./use-events";
import { PageConfig } from "@/components/schema-form-render/meta";
import { SchemaFormSearchContent } from "@/components/schema-form-render/components/schema-form-content";
import { useScemaRender } from "../utils";
import { CreateModalListHoc } from "hoc-form";
import DrawerForm from "./drawer-form";
import { getSubmitFormValues } from "@ey-utils/utils/formily-utils/getSubmitFormValues";

export const CreateModalList: CreateModalListHoc = (fcProps) => (props) => {
  const F = React.useRef<any>();
  const dataRef = React.useRef<any>([]);
  const {
    metasConfig,
    modalMetasConfig,
    noModal = true,
    pageApi,
    dealMetaBeforeRender,
    dealModalMetasBeforeRender,
    events,
    handleSave,
    api,
    pageCode,
    rowSelection = null,
    rowKey,
    noTableOpCol = false,
    modalCode = "",
    modalDetilCode = "",
    noQueryKeys = false,
    noCache = false,
    match,
    history,
    extraPrams,
    filedConfig,
    formConfigs,
    operWidth,
    editable = false,
    editableIdKey,
    editableColsMap,
    onEditableRowSave,
    nested = false,
    nestedTableColumns = [],
    nestedTableDataKey = "",
    formatSearchData,
    modalfiledConfig,
    modalformConfigs,
    modalWidth,
    rowsRender,
    reloadFlag,
    onCancel,
    validator,
    showWay = "modal",
    needGroup = false,
    clearSelectedRowKeys,
    resetColumns,
    queryDataFunc,
  } = _.merge(fcProps, props);
  const [remoteMetasConfig, setRemoteMetasConfig] = useState<PageConfig>({
    labelAlign: "right",
    layout: 3,
    pageDatas: [],
  });
  const [
    remoteModalMetasConfig,
    setRemoteModalMetasConfig,
  ] = useState<PageConfig>({
    labelAlign: "right",
    layout: 3,
    pageDatas: [],
  });
  const { form, SchemaFormRender } = useScemaRender(filedConfig, formConfigs);
  F.current = form;
  // search 初始值
  const [searchValue, setSearchValue] = useState<any>({});
  // 弹窗控制
  const [visible, setVisible] = useState(false);
  const [title, setTitle] = useState("新增");
  // 设置页面的编辑属性
  const [type, setType] = useState<any>("");
  const [editData, setEditData] = useState<null | any>(null);
  // 规则类型选项
  const [loading, setLoading] = useState(false);
  const [tData, setData] = useState<any>([]);
  useEffect(() => {
    dataRef.current = tData;
  }, [tData]);
  // 表格多选单选
  const [selectedRowKeys, setselectedRowKeys] = useState<string[]>([]);
  const [selectedRows, setselectedRows] = useState<any[]>([]);
  const apiRef = React.useRef();
  const hookMapIns = React.useRef({
    tableButtonsEvents: {
      // 列-查看详情按钮点击事件
      handleViewClick: (id: string, row: any) => {
        if (!noModal) {
          setType("DETAIL");
          setTitle("查看");
          // 获取参数
          const da = {};
          Object.keys(api?.param).forEach((i: any) => {
            da[i] = row[i] || api.param[i];
          });
          apiRef.current = {
            ...api,
            ...{ param: da },
          };
          setVisible(true);
        }
      },
      // 列-编辑按钮点击事件
      handleEditClick: async (id: string, row: any) => {
        if (!noModal) {
          setVisible(true);
          setTitle("编辑");
          setEditData(row);
        }
      },
      // 打印
      printPdf: (id: string, row: any) => {
        window.open(
            `#/micro-app?name=asm&url=/print/${row.code}/${row.type}`
        );
      },
      // 列-删除按钮点击事件
      handleColDleClick: async (id: string, row: any) => {},
      // 列-启用按钮点击事件
      handleEnableClick: async (id: string, row: any) => {},
      // 列-禁用按钮点击事件
      handleDisableClick: async (id: string, row: any) => {},
    },
    buttonsEvents: {
      // 重置
      reset: () => {
        F?.current?.reset();
        storage.updateItem(match?.path, { queryKeys: {}, pageNo: 1 });
        loadData({}, 1, 10);
      },
      // 搜索按钮点击事件
      handleSearchClick: () => {
        getSubmitFormValues(F?.current).then((values) => {
          if (noCache) {
            loadData({ ...values }, 1, 10);
            return;
          }
          const st = storage.getItem(match?.path);
          storage.updateItem(match?.path, {
            queryKeys: values,
            pageNo: 1,
            pageSize: st?.pageSize || 10,
          });
          loadData({ ...values }, 1, st?.pageSize || 10);
        });
      },
      // 新增是否使用弹窗
      handleCreateBtnClick: () => {
        if (!noModal) {
          setTitle("新增");
          setVisible(true);
        }
      },
      // 列-删除按钮点击事件
      handleColDleClick: async (id: string, row: any) => {
        const values = F?.current?.values;
        const page: any = storage.getItem(match?.path);
        loadData({ ...values }, page.pageNo, page?.pageSize || 10);
      },
      // 导出值
      handleExport: () => {},
      // 导入值
      handleImport: () => {},
      // 列表选中
      handleReversalBtn: async () => {},
    },
  });
  const {
    schema,
    searchButtons,
    tableColumns,
    buttons,
    tableButtons,
    pageConfig,
  } = useInitData(metasConfig, remoteMetasConfig);

  const baseRowSelection = {
    selectedRowKeys,
    onChange: (keys: string[], rows: any[]) => {
      setselectedRowKeys(keys);
      setselectedRows(rows);
      rowSelection?.onChange && rowSelection.onChange(keys, rows);
    },
  };

  // 获取 row配置信息
  const getRowSelectionConfig = () => {
    if (rowSelection) {
      return {
        ...rowSelection,
        ...baseRowSelection,
        // ...rowSelection,
      };
    }
    return null;
  };
  // 初始化数据
  const loadData = async (queryData: any, pageNo: number, pageSize: number) => {
    if (!pageApi) return;
    setLoading(true);
    const queryKeys = formatSearchData
      ? formatSearchData(queryData)
      : { ...queryData };
    try {
      const queryParams = {
        queryKeys: {
          ...queryKeys,
          ...(extraPrams || {}),
          pageCode,
        },
        pageNo,
        pageSize,
        // TODO:后台处理额外参数统一放外层
        ...(noQueryKeys ? { ...queryKeys, ...(extraPrams || {}) } : {}),
      };

      const res: any = queryDataFunc
        ? await queryDataFunc(queryParams)
        : await xhrPostJson(pageApi, queryParams);
      setData({ ...res?.result, number: pageNo });
      setLoading(false);
      setselectedRowKeys([]);
      clearSelectedRowKeys && clearSelectedRowKeys();
    } catch (err) {
      setLoading(false);
    }
  };

  // 分页搜索
  const search = (current: number, pageSize: number) => {
    const vs = F.current.values;
    loadData({ ...vs }, current, pageSize);
    storage.setItem(match?.path, {
      queryKeys: { ...vs },
      pageNo: current,
      pageSize,
    });
  };

  // 搜索缓存逻辑
  const handleSearchData = (dt: any = {}) => {
    getSubmitFormValues(F?.current).then((vals) => {
      const vs = _.omitBy(vals, _.isNull);
      const values = {
        ...dt,
        ...vs,
      };
      storage.setItem(props?.match?.path, { queryKeys: { ...values } });
      if (noCache) {
        loadData({ ...values, ...dt }, 1, 10);
        return;
      }
      const page: any = storage.getItem(match?.path);
      if (!page?.pageNo) {
        page.pageNo = 1;
      }
      if (!page?.pageSize) {
        page.pageSize = 10;
      }
      loadData({ ...values, ...dt }, page.pageNo, page.pageSize);
      storage.setItem(match?.path, {
        queryKeys: { ...values, ...dt },
        ...page,
      });
    });
  };

  // 事件注册
  const { getSearchButtons, getTableTopButton, operations } = useEventsRegister(
    hookMapIns,
    events,
    {
      history,
      pageCode,
      callback: (flag: boolean = true) => {
        if (flag) {
          const page: any = storage.getItem(match?.path);
          search(page.pageNo || 1, page?.pageSize || 10);
        } else {
          search(1, 10);
        }
      },
      noModal,
      tableButtons,
      buttons,
      searchButtons,
      loading,
      setLoading,
      hookMapIns,
      validator,
      match,
      dataRef,
    }
  );
  // 初始化请求页面数据
  const initData = () => {
    const page: any = storage.getItem(match?.path);
    if (noCache) {
      handleSearchData();
    } else if (page && page.queryKeys) {
      // 特殊处理时间初始化
      if (page.queryKeys.vt) {
        page.queryKeys.vt = moment(page.queryKeys.vt);
      }
      setSearchValue({
        ...page.queryKeys,
      });
      handleSearchData(page.queryKeys);
    } else {
      handleSearchData();
    }
  };

  useEffect(() => {
    console.log("redloading------------>reloadFlag", extraPrams, reloadFlag);

    if (form?.id) {
      // handleSearchData();
      initData();
      return;
    }
  }, [JSON.stringify(extraPrams), reloadFlag, form?.id]);

  // 获取 metasConfig
  useEffect(() => {
    if (pageCode || modalCode) {
      try {
        if (pageCode) {
          getPageMeta(pageCode || "").then((res: any) => {
            if (res.success) {
              if (dealMetaBeforeRender) {
                dealMetaBeforeRender(res.result);
              }
              setRemoteMetasConfig(res.result);
            }
          });
        }

        if (modalCode) {
          getPageMeta(modalCode).then((res: any) => {
            if (res.success) {
              if (dealModalMetasBeforeRender) {
                dealModalMetasBeforeRender(res.result);
              }
              setRemoteModalMetasConfig(res.result);
            }
          });
        }
      } catch (err) {
        console.error("请求出错", err);
      }
    }
  }, [pageCode, modalCode]);

  // 获取 Modal metas
  const getModalMetas = (): any => {
    const opMetas = modalCode
      ? remoteModalMetasConfig || []
      : modalMetasConfig || [];
    return opMetas;
  };
  const ShowWay = showWay === "modal" ? ModalFormWrap : DrawerForm;
  return (
    <>
      <SchemaFormSearchContent footer={getSearchButtons()}>
        {SchemaFormRender && (
          <SchemaFormRender schema={schema} pageConfig={pageConfig} />
        )}
      </SchemaFormSearchContent>
      <TableRender
        rowKey={rowKey || "id"}
        metas={tableColumns || []}
        rowSelection={getRowSelectionConfig()}
        match={match}
        isRequesting={loading}
        handleSearch={search}
        extraAction={getTableTopButton()}
        operation={noTableOpCol ? null : operations}
        operWidth={operWidth}
        operAuths={tableButtons?.map(() => "")}
        data={tData || []}
        editable={editable}
        editableIdKey={editableIdKey}
        editableColsMap={editableColsMap}
        onEditableRowSave={onEditableRowSave}
        nested={nested}
        nestedTableColumns={nestedTableColumns}
        nestedTableDataKey={nestedTableDataKey}
        rowsRender={rowsRender}
        resetColumns={resetColumns}
      />
      {!noModal && type !== "DETAIL" && (
        <ShowWay
          title={title}
          editData={editData}
          loading={loading}
          visible={visible}
          width={modalWidth}
          modalMetasConfig={getModalMetas()}
          filedConfig={modalfiledConfig}
          formConfigs={modalformConfigs}
          onCancel={() => {
            setEditData(null);
            setVisible(false);
            onCancel && onCancel();
          }}
          onOk={async (values: any, cb: any) => {
            setLoading(true);
            if (title === "编辑") {
              values.id = editData.id;
              values.viewType = "EDIT";
            } else {
              values.viewType = "ADD";
            }
            try {
              if (handleSave) {
                const res = await handleSave(values);
                if (res.success) {
                  setVisible(false);
                  message.success("保存成功");
                  handleSearchData();
                  setEditData(null);
                  if (cb) cb();
                }
              }
              setLoading(false);
            } catch (err) {
              setLoading(false);
            }
          }}
        />
      )}
      {!noModal && type === "DETAIL" && (
        <ModalDetailForm
          title={title}
          api={apiRef.current}
          visible={visible}
          filedConfig={modalfiledConfig}
          formConfigs={modalformConfigs}
          needGroup={needGroup}
          onCancel={() => {
            setType("");
            setEditData(null);
            setVisible(false);
            onCancel && onCancel();
          }}
        />
      )}
    </>
  );
};

export const WithListComp = CreateModalList({});
